package com.ch.web.mq;

import com.ch.web.entity.user.XyUserEntity;
import com.ch.web.requestDto.xyUser.RegisterFormDto;
import com.ch.web.service.XyUserService;
import lombok.Data;
import lombok.Setter;
import org.springframework.stereotype.Component;

import java.util.concurrent.locks.ReentrantLock;

@Data
@Component
public class RegisterUserMqHandlerService implements HandlerRabbitMq {
    @Setter
    XyUserService xyUserService;

    public RegisterUserMqHandlerService() {
    }

    private final ReentrantLock reentrantLock = new ReentrantLock();

    @CutosListerMq(MqCustomConfigure.REGIS_USER)
    @Override
    public void receiveMsg(MessageRegister messageRegister) {
        reentrantLock.lock();
        ResultMessage resultMessage;
        try {
            Object data = messageRegister.getData();
            RegisterFormDto formDto = (RegisterFormDto) data;
            XyUserEntity userByRegisterDto = XyUserEntity.createUserByRegisterDto(formDto);
            xyUserService.save((userByRegisterDto));
            messageRegister.setStatus(true);
            resultMessage = ResultMessage.successCreate(messageRegister, "success");
            RabbitMqCustomTemplate.getCallQueue().add(resultMessage);
        } catch (Exception e) {
            resultMessage = ResultMessage.failCreate(messageRegister, e.getMessage());
            RabbitMqCustomTemplate.getCallQueue().add(resultMessage);
        } finally {
            reentrantLock.unlock();
        }
    }
}
